package Entity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ExerciseGenerator {
    private static final Random RANDOM = new Random();
    private static ExerciseGenerator instance;

    private ExerciseGenerator() {}

    public static ExerciseGenerator getInstance() {
        if (instance == null) {
            instance = new ExerciseGenerator();
        }
        return instance;
    }

    // 生成加法习题（使用统一的Exercise构造函数生成ID）
    public List<Exercise> generateAddExercises(int count, String date) throws IOException {
        List<Exercise> exerciseList = new ArrayList<>();
        String type = "Add";
        checkAndCreateBaseDir();
        String seq = CsvFileUtil.getNextSeq(date, type);
        String filePath = CsvFileUtil.BASE_DIR + "Exercise_" + type + "_" + date + "_" + seq + ".csv";

        for (int i = 0; i < count; i++) {
            int num2 = RANDOM.nextInt(101);
            int num1 = RANDOM.nextInt(101 - num2);
            int correctAnswer = num1 + num2;
            // 调用统一构造函数，确保ID格式正确（type=Add, date=20231001, seq=001, questionNo=i+1）
            Exercise exercise = new Exercise(type, date, seq, i + 1, num1, '+', num2, correctAnswer);
            exerciseList.add(exercise);
        }

        CsvFileUtil.writeExerciseToCsv(exerciseList, filePath);
        return exerciseList;
    }

    // 生成减法习题（同理，统一ID格式）
    public List<Exercise> generateSubExercises(int count, String date) throws IOException {
        List<Exercise> exerciseList = new ArrayList<>();
        String type = "Sub";
        checkAndCreateBaseDir();
        String seq = CsvFileUtil.getNextSeq(date, type);
        String filePath = CsvFileUtil.BASE_DIR + "Exercise_" + type + "_" + date + "_" + seq + ".csv";

        for (int i = 0; i < count; i++) {
            int num1 = RANDOM.nextInt(101);
            int num2 = RANDOM.nextInt(num1 + 1);
            int correctAnswer = num1 - num2;
            Exercise exercise = new Exercise(type, date, seq, i + 1, num1, '-', num2, correctAnswer);
            exerciseList.add(exercise);
        }

        CsvFileUtil.writeExerciseToCsv(exerciseList, filePath);
        return exerciseList;
    }

    // 生成混合习题（修复ID格式：统一为 类型_日期_序号_题号）
    public List<Exercise> generateMixExercises(int count, String date) throws IOException {
        List<Exercise> exerciseList = new ArrayList<>();
        String type = "Mix";
        checkAndCreateBaseDir();
        String seq = CsvFileUtil.getNextSeq(date, type);
        String filePath = CsvFileUtil.BASE_DIR + "Exercise_" + type + "_" + date + "_" + seq + ".csv";

        int addCount = count / 2;
        int subCount = count - addCount;

        // 混合习题的加法题：ID格式 Add_日期_序号_题号（如 Add_20231001_001_001）
        for (int i = 0; i < addCount; i++) {
            int num2 = RANDOM.nextInt(101);
            int num1 = RANDOM.nextInt(101 - num2);
            int correctAnswer = num1 + num2;
            Exercise exercise = new Exercise("Add", date, seq, i + 1, num1, '+', num2, correctAnswer);
            exerciseList.add(exercise);
        }

        // 混合习题的减法题：ID格式 Sub_日期_序号_题号（如 Sub_20231001_001_006）
        for (int i = 0; i < subCount; i++) {
            int num1 = RANDOM.nextInt(101);
            int num2 = RANDOM.nextInt(num1 + 1);
            int correctAnswer = num1 - num2;
            Exercise exercise = new Exercise("Sub", date, seq, addCount + i + 1, num1, '-', num2, correctAnswer);
            exerciseList.add(exercise);
        }

        CsvFileUtil.writeExerciseToCsv(exerciseList, filePath);
        return exerciseList;
    }

    // 随机抽取3套习题（保持不变）
    public List<String> randomSelectThreeExercises(String currentDate) {
        File dir = new File(CsvFileUtil.BASE_DIR);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("存储目录不存在，无法抽取习题：" + CsvFileUtil.BASE_DIR);
        }

        File[] exerciseFiles = dir.listFiles(file -> {
            if (!file.isFile() || !file.getName().endsWith(".csv")) return false;
            String fileName = file.getName();
            if (!fileName.startsWith("Exercise_")) return false;
            String[] parts = fileName.split("_");
            if (parts.length < 4) return false;
            String generateDate = parts[2];
            return generateDate.compareTo(currentDate) <= 0;
        });

        if (exerciseFiles == null || exerciseFiles.length < 3) {
            throw new IllegalArgumentException("习题文件不足3套，当前可用：" + (exerciseFiles == null ? 0 : exerciseFiles.length) + "套");
        }

        List<File> fileList = new ArrayList<>(List.of(exerciseFiles));
        java.util.Collections.shuffle(fileList);
        List<String> selectedPaths = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            selectedPaths.add(fileList.get(i).getAbsolutePath());
        }

        System.out.println("今日随机抽取3套习题：");
        for (String path : selectedPaths) {
            System.out.println(path);
        }
        return selectedPaths;
    }

    // 目录校验辅助方法（保持不变）
    private void checkAndCreateBaseDir() {
        File baseDir = new File(CsvFileUtil.BASE_DIR);
        if (!baseDir.exists()) {
            boolean createSuccess = baseDir.mkdirs();
            if (createSuccess) {
                System.out.println("✅ 存储目录不存在，已自动创建：" + CsvFileUtil.BASE_DIR);
            } else {
                throw new RuntimeException("❌ 无法创建存储目录：" + CsvFileUtil.BASE_DIR + "，请检查路径权限");
            }
        }
        if (!baseDir.isDirectory()) {
            throw new RuntimeException("❌ 存储路径不是文件夹：" + CsvFileUtil.BASE_DIR + "，请修改路径");
        }
    }
}